package com.xique.blelock.Jpush;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.xique.MyApplication;
import com.xique.blelock.NetUtils.NetResult;
import com.xique.blelock.NetUtils.XqNetClient;
import com.xique.blelock.R;
import com.xique.blelock.Utils.ACache;
import com.xique.blelock.Utils.Stringkey;
import com.xique.blelock.Utils.TimeUtil;
import com.xique.blelock.model.HistoryMessageInfo;
import com.xique.blelock.model.MessageInfo;
import com.xique.blelock.model.MessageType;
import com.xique.blelock.model.UnreadMessage;
import com.xique.blelock.model.UserInfo;
import com.xique.blelock.view.Setting.HuodongActiviy;
import com.xique.blelock.view.Setting.Message_Activity;
import com.xique.blelock.view.Setting.SystemNotifiActiviy;
import com.xique.blelock.view.Setting.devicemessages;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.logging.Logger;

import cn.jpush.android.api.JPushInterface;
import me.leolin.shortcutbadger.ShortcutBadger;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.xique.blelock.model.MessageType.Device_SubType_AddDevice;
import static com.xique.blelock.model.MessageType.Device_SubType_DeleDevice;

/**
 * Created by Administrator on 2018/12/26.
 */

public class JpushReceiver extends BroadcastReceiver {
    private static final String TAG = "JpushReceiver";
    private UserInfo userInfo;
    private NotificationManager nm;

    public JpushReceiver() {
        super();

    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (null == nm) {
            nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        }
        userInfo = (UserInfo) ACache.get(context).getAsObject(Stringkey.USERInfo);

        //加一个推送管理类
//        if(Build.VERSION.SDK_INT >=26){
////            Bundle bundle = intent.getExtras();
//            Log.e("DDZTAG","8.0处理了");
//            NotificationManager notificationManager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
//            String id=context.getPackageName();
//            CharSequence name=context.getString(R.string.app_name);
//            int importance=NotificationManager.IMPORTANCE_HIGH;
//            NotificationChannel channel=new NotificationChannel(id,name,importance);
//            channel.enableLights(true);
//            channel.setLightColor(Color.RED);
//            channel.enableVibration(true);
//            channel.setShowBadge(true);
//            channel.setVibrationPattern(new long[]{100,200,300,400,500,400,300,200,400});
//            notificationManager.createNotificationChannel(channel);
//            int notificationId = 0x1234;
//            Notification.Builder builder = new Notification.Builder(context,id); //与channelId对应
//            //icon title text必须包含，不然影响桌面图标小红点的展示
//
//
//        }else
//            if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {

            Bundle bundle = intent.getExtras();
            Log.e(TAG, "onReceive - " + intent.getAction() + ", extras: " + bundle.toString());

            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
                Log.e(TAG, "JPush 用户注册成功");

            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                Log.e(TAG, "接受到推送下来的自定义消息");

            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
                Log.e(TAG, "接受到推送下来的通知");

                receivingNotification(context, bundle);


            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                Log.e(TAG, "用户点击打开了通知");

                openNotification(context, bundle);

            } else {
                Log.e(TAG, "Unhandled intent - " + intent.getAction());
            }
//        }
    }

    private void receivingNotification(Context context, Bundle bundle){
        String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);
        Log.e(TAG, " title : " + title);
        String message = bundle.getString(JPushInterface.EXTRA_ALERT);
        Log.e(TAG, "message : " + message);
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);

        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(extras);
        HistoryMessageInfo historyMessageInfo = jsonObject.getJSONObject(Stringkey.JpushKey).toJavaObject(HistoryMessageInfo.class);
        String PushAction = null;
        if(historyMessageInfo.getType() == MessageType.device){
            PushAction  = Stringkey.Device_Message_Event;
        }else if(historyMessageInfo.getType() == MessageType.system){
            PushAction  = Stringkey.System_Message_Event;
        }else if( historyMessageInfo.getType() == MessageType.actitivity){
            PushAction  = Stringkey.Activity_Message_Event;
        }
        if(PushAction != null) {
            Intent intent = new Intent();
            intent.putExtra(Stringkey.JpushKey, historyMessageInfo);
            intent.setAction(PushAction);
            context.sendBroadcast(intent);

            Intent intent1 = new Intent();
            intent1.setAction(Stringkey.Message_Event);
            context.sendBroadcast(intent1);

            //标记当前有新信息
            ACache.get(MyApplication.context).put(Stringkey.HasMessage, true);

            //如果是设备上出增加，需要通知主页面
            if(historyMessageInfo.getType() == MessageType.device)
            {
                if(historyMessageInfo.getSubType() == Device_SubType_AddDevice
                        || historyMessageInfo.getSubType() == Device_SubType_DeleDevice){
                        //通知主页
                    Intent intent3 = new Intent();
                    intent3.setAction(Stringkey.Device_ReGetDeviceList);
                    context.sendBroadcast(intent3);
                }
            }
        }
        getUnreadMessage(context);
        Log.e(TAG, "historyMessageInfo : " + com.alibaba.fastjson.JSONObject.toJSONString(historyMessageInfo));

    }

    private void getUnreadMessage(final Context context) {
        //getUnreadMessageCount
        XqNetClient netClient =  new XqNetClient();
        JSONObject jsonobject = new JSONObject();
        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        netClient.getUnreadMessageCount(jsonobject.toString()).enqueue(new Callback<NetResult<List<UnreadMessage>>>(){//获取验证码
            @Override
            public void onResponse(Call<NetResult<List<UnreadMessage>>> call, Response<NetResult<List<UnreadMessage>>> response) {

                if(response.body().isSuccess()){
                    List<UnreadMessage> unreadMessageList = response.body().getData();
                    if (unreadMessageList != null && (unreadMessageList.size() >0)) {
                        int badgeCount = 0;
                        for(UnreadMessage unreadMessage: unreadMessageList){
                            badgeCount += unreadMessage.getUnReadCount();
                        }
                        ShortcutBadger.applyCount(context, badgeCount); //for 1.1.4+
                    }

                }

            }

            @Override
            public void onFailure(Call<NetResult<List<UnreadMessage>>> call, Throwable t) {
                t.printStackTrace();

            }
        });
    }

    private void openNotification(Context context, Bundle bundle){
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        String myValue = "";
        try {
            JSONObject extrasJson = new JSONObject(extras);
            myValue = extrasJson.optString("myKey");
            Log.e(TAG, "extras : " + extrasJson);
        } catch (Exception e) {
            Log.e(TAG, "Unexpected: extras is not a valid json", e);
            return;
        }
        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(extras);
        HistoryMessageInfo historyMessageInfo = jsonObject.getJSONObject(Stringkey.JpushKey).toJavaObject(HistoryMessageInfo.class);
        if(historyMessageInfo != null){
            startActivity(context,historyMessageInfo);
        }
        ShortcutBadger.removeCount(context); //for 1.1.4+

    }

    private void startActivity(Context context, HistoryMessageInfo historyMessageInfo){
        Class activity = null;
        if(historyMessageInfo.getType() == MessageType.device){
            activity = devicemessages.class;
        }else if(historyMessageInfo.getType() == MessageType.system){
            activity = SystemNotifiActiviy.class;
        }else if( historyMessageInfo.getType() == MessageType.actitivity){
            activity = HuodongActiviy.class;
        }
        if(activity == null){
            return;
        }
        Intent mIntent = new Intent(context, activity);
            mIntent.putExtra(Stringkey.Message, true);
            context.startActivity(mIntent);
    }
}
